import React, { useState, useEffect, useCallback } from 'react';
import { Button, Table, Modal, Form, Input, notification, Row, Col, Switch, Tooltip } from 'antd';
import { fetchApi } from '../../general/api';
import SelectControllers from '../alert/alarm_config_group_select';
import SelectDynamicType from "../../general/type_select";
import { CheckCircleOutlined, StopOutlined, AudioOutlined, AudioMutedOutlined } from '@ant-design/icons';

interface AlarmConfig {
    alarm_config_id: number;
    alarm_config_group_id: number;
    alarm_config_name: string;
    alarm_config_formula: string;
    alarm_config_action: string;
    alarm_correct_value: string;
    alarm_judgment_formula: string;
    alarm_status: string;
    alarm_config_level_type: string;
}

const ManageAlarmConfig: React.FC = () => {
    const [probeList, setprobeList] = useState<AlarmConfig[]>([]); // 项目列表
    const [selectedRows, setSelectedRows] = useState<AlarmConfig[]>([]); // 选中行
    const [alarmConfigId, setAlarmConfigId] = useState<number>(0); // 设为 0 或其他合适的初始值
    const [isEditMode, setIsEditMode] = useState(false); // 编辑模式状态
    const [isModalOpen, setIsModalOpen] = useState(false); // 弹框显示状态
    const [form] = Form.useForm(); // 表单实例
    const [alarmConfigGroupCode, setAlarmConfigGroupCode] = useState<string>(''); // 新增状态保存 alarm_config_group_code
    // 表格列定义

    const getTableColumns = () => [
        {
            title: '', // 空标题
            dataIndex: 'alarm_status', // 假设返回值中有 `status` 字段
            width: 30,
            render: (status: string | number) => {
                let icon, tooltipText;

                // 根据状态值动态显示小图标
                if (status === 1) {
                    icon = <AudioOutlined style={{ color: 'green', fontSize: '16px' }} />;
                    tooltipText = '开启'
                } else {
                    icon = <AudioMutedOutlined style={{ color: 'gray', fontSize: '16px' }} />;
                    tooltipText = '关闭'
                }
                // Tooltip 包裹图标
                return (
                    <Tooltip title={tooltipText}>
                        {icon}
                    </Tooltip>
                );
            },
        },
        { title: '探针名称', dataIndex: 'alarm_config_name', width: 150 },
        { title: '执行动作', dataIndex: 'alarm_config_action', width: 150 },
        { title: '告警判断', dataIndex: 'alarm_judgment_formula', width: 150 },
        { title: '告警阈值', dataIndex: 'alarm_correct_value', width: 150 },
        { title: '告警级别', dataIndex: 'alarm_config_level_type', width: 150 },
        { title: '备注', dataIndex: 'alarm_config_instruction', width: 150 },
    ].map((col) => ({
        ...col,
        ellipsis: true,
        render: col.render || ((text: string | React.ReactNode) => (
            <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'block' }}>
                {text}
            </span>
        )),
    }));


    // 处理选择控制器时更新 alarm_config_group_code, 与设置选中值
    const handleCityChange = (value: string, label: string, alarmConfigGroupCode: string) => {
        form.setFieldsValue({ alarm_config_group_id: value });
        setAlarmConfigGroupCode(alarmConfigGroupCode); // 更新 alarm_config_group_code
    };

    // 获取项目列表数据
    // 重新加载数据时，清空选中的行并重新选中
    const fetchprobeList = useCallback(async () => {
        try {
            const response_data = await fetchApi('/easymonitor/api/probe', {
                method: 'GET',
            });
            setprobeList(response_data);
            setSelectedRows([]); // 重新加载数据时清空选中的行
        } catch (error) {
            notification.error({
                message: '请求失败',
                description: `获取项目列表失败: ${error}`,
                duration: 2,
            });
        }
    }, []);

    // 显示通知
    const showNotification = (type: 'success' | 'error' | 'warning', message: string, description: string) => {
        notification[type]({ message, description, duration: 2 });
    };

    // 打开新增/编辑弹框
    const openModal = (record: AlarmConfig | null = null) => {
        setIsModalOpen(true);
        setIsEditMode(!!record);
        if (record) {
            setAlarmConfigId(record.alarm_config_id);
            setTimeout(() => {
                form.setFieldsValue({
                    ...record,
                    alarm_config_action: String(record.alarm_config_action), // 确保类型一致
                });
            }, 0);
        } else {
            setAlarmConfigId(0);
            form.resetFields(); // 新增时清空表单
        }
    };

    // 关闭弹框
    const closeModal = () => {
        setIsModalOpen(false);
        form.resetFields();
    };

    // 提交表单后，保存成功，确保重新选中当前编辑的行
    const handleSubmit = async (values: AlarmConfig) => {
        try {
            const method = isEditMode ? 'PUT' : 'POST';
            const endpoint = '/easymonitor/api/probe'; // 修改为实际接口

            // 如果是编辑模式，确保 alarm_config_id 存在
            if (isEditMode) {
                values.alarm_config_id = alarmConfigId;
            }

            await fetchApi(endpoint, {
                method,
                body: JSON.stringify(values),
            });

            notification.success({
                message: isEditMode ? '编辑成功' : '新增成功',
                duration: 2,
            });
            closeModal();
            fetchprobeList(); // 保存成功后重新加载数据
        } catch (error: unknown) {
            if (error instanceof Error) {
                notification.error({
                    message: '操作失败',
                    description: error.message,
                    duration: 2,
                });
            } else {
                notification.error({
                    message: '操作失败',
                    description: '发生了未知错误',
                    duration: 2,
                });
            }
        }
    };

    // 删除选中的项目
    const handleDelete = async () => {
        if (selectedRows.length === 0) {
            showNotification('warning', '警告', '请选择至少一条记录进行删除！');
            return;
        }

        Modal.confirm({
            title: '确认删除',
            content: `确定要删除选中的 ${selectedRows.length} 个项目吗？`,
            onOk: async () => {
                try {
                    await fetchApi('/easymonitor/api/probe', {
                        method: 'DELETE',
                        body: JSON.stringify(selectedRows),
                    });

                    showNotification('success', '删除成功', '选中的项目已成功删除。');
                    fetchprobeList();
                    setSelectedRows([]);
                } catch (error) {
                    showNotification('error', '删除失败', `删除操作失败: ${error}`);
                }
            },
        });
    };

    // 初始化加载数据
    useEffect(() => {
        fetchprobeList();
    }, [fetchprobeList]);

    return (
        <div style={{ display: 'flex', flexDirection: 'column', minHeight: '700px' }}>
            {/* 按钮区 */}
            <div style={{ marginBottom: '16px', display: 'flex', gap: '8px' }}>
                <Button type="primary" onClick={() => openModal()}>新增</Button>
                <Button
                    onClick={() => {
                        if (selectedRows.length !== 1) {
                            showNotification('warning', '警告', '请选择一条记录进行编辑！');
                        } else {
                            openModal(selectedRows[0]);
                        }
                    }}
                >
                    编辑
                </Button>
                <Button danger onClick={handleDelete}>删除</Button>
            </div>

            {/* 表格区 */}
            <Table
                size="small"
                columns={getTableColumns()}
                dataSource={probeList}
                rowKey="alarm_config_id"
                pagination={{ position: ['bottomCenter'], pageSize: 12 }}
                rowSelection={{
                    type: 'checkbox',
                    selectedRowKeys: selectedRows.map((row) => row.alarm_config_id),
                    onChange: (_, rows) => setSelectedRows(rows),
                }}
                onRow={(record) => ({
                    onClick: () => {
                        const isSelected = selectedRows.some((row) => row.alarm_config_id === record.alarm_config_id);
                        const updatedRows = isSelected
                            ? selectedRows.filter((row) => row.alarm_config_id !== record.alarm_config_id)
                            : [...selectedRows, record];
                        setSelectedRows(updatedRows);
                    },
                })}
                style={{ overflowX: 'auto' }}
                locale={{ emptyText: '暂无数据' }}
            />

            {/* 新增/编辑弹框 */}
            <Modal
                title={isEditMode ? '编辑探针' : '新增探针'}
                open={isModalOpen}
                onOk={() => form.submit()}
                onCancel={closeModal}
                destroyOnClose
                width="40%"  // Modal宽度
            >
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleSubmit}
                    initialValues={{ alarm_status: 1 }}
                >
                    <Form.Item
                        label="告警组ID"
                        name="alarm_config_id"
                        style={{ display: 'none' }}  // 隐藏该字段
                    >
                        <Input type="hidden" value={alarmConfigId} />
                    </Form.Item>
                    {/* 项目名和项目ID并排 */}
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                label="探针名称"
                                name="alarm_config_name"
                                rules={[{ required: true, message: '请输入探针名称！' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="控制器绑定"
                                name="alarm_config_group_id"
                                rules={[{ required: true, message: '请绑定一个控制器' }]}
                            >
                                <Form.Item shouldUpdate={(prev, curr) => prev.alarm_config_group_id !== curr.alarm_config_group_id}>
                                    {({ getFieldValue }) => (
                                        <SelectControllers
                                            selectedCity={getFieldValue('alarm_config_group_id') || ''} // 动态获取当前值
                                            onCityChange={handleCityChange}
                                            style={{ width: '100%' }}
                                        />
                                    )}
                                </Form.Item>
                            </Form.Item>
                        </Col>
                    </Row>

                    {/* 告警组URL和连接类型并排 */}
                    <Row gutter={16}>
                        <Col span={16}>
                            <Form.Item
                                label="配置公式"
                                name="alarm_config_formula"
                                rules={[{ message: '请输入配置公式' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                label="执行动作"
                                name="alarm_config_action"
                                rules={[{ required: true, message: '请选择一个执行动作！' }]}
                            >
                                <SelectDynamicType
                                    codeParentValue={alarmConfigGroupCode}
                                    codeType="probe_action_type"
                                    style={{ width: '100%' }}
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={16}>
                            <Form.Item
                                label="告警阈值"
                                name="alarm_correct_value"
                                rules={[{ required: true, message: '请输入阈值！' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                label="告警判断 (满足则告警)"
                                name="alarm_judgment_formula"
                                rules={[{ required: true, message: '请选择一个判断方式！' }]}
                            >
                                <SelectDynamicType
                                    codeType="comparison_type"
                                    style={{ width: '100%' }}
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={16}>
                            <Form.Item
                                label="告警级别"
                                name="alarm_config_level_type"
                                rules={[{ required: true, message: '请选择告警级别' }]}
                            >
                                <SelectDynamicType
                                    codeType="alarm_level_type"
                                    style={{ width: '100%' }}  // 使下拉框宽度自适应
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                label="开关"
                                name="alarm_status"
                                initialValue={false}
                            >
                                <Switch
                                    checkedChildren="开启"
                                    unCheckedChildren="关闭"
                                    onChange={(checked) => form.setFieldsValue({ alarm_status: checked ? 1 : 0 })}
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Form.Item
                        label="备注"
                        name="alarm_config_instruction"
                    >
                        <Input.TextArea />
                    </Form.Item>
                </Form>
            </Modal>
        </div >
    );
};

export default ManageAlarmConfig;
